<?php

declare(strict_types=1);

namespace App\Admin;

use App\Entity\AdminUser;
use App\Entity\LogType;
use App\Utils\Helper\GetterHelper;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Symfony\Component\Security\Core\Security;

final class LogAdmin extends AbstractAdmin {
    protected $baseRouteName = 'admin_log';
    protected $baseRoutePattern = 'log';
    protected $maxPageLinks = 10;
    protected $security;

    public function __construct ($code, $class, $baseControllerName, Security $security) {
        parent::__construct($code, $class, $baseControllerName);

        $this->security = $security;
    }

    protected function configureDefaultSortValues (array &$sortValues) {
        $sortValues['_page'] = 1;
        $sortValues['_per_page'] = 32;
        $sortValues['_sort_order'] = 'DESC';
        $sortValues['_sort_by'] = 'id';
    }

    protected function configureDatagridFilters (DatagridMapper $datagridMapper): void {
        $datagridMapper
            ->add('log_type_id', 'doctrine_orm_choice', [
                'label'       => '日志类型',
                'show_filter' => true,
            ], ChoiceType::class, [
                'choices' => array_flip(GetterHelper::getEntityManager()->getRepository(LogType::class)->findAllToArray()),
            ])
            ->add('admin_user_id', 'doctrine_orm_choice', [
                'label'       => '系统用户',
                'show_filter' => true,
            ], ChoiceType::class, [
                'choices' => array_flip(GetterHelper::getEntityManager()->getRepository(AdminUser::class)->findAllToArray()),
            ])
            ->add('created_at', CallbackFilter::class, [
                'label'       => '日期',
                'show_filter' => true,
                'callback'    => [$this, 'getCreatedAtFilter'],
            ], null, [
                'attr' => [
                    'readonly' => 'readonly',
                    'style'    => 'background-color: #fff',
                ],
            ]);
    }

    public function getCreatedAtFilter ($queryBuilder, $alias, $field, $value) {
        if (!$value['value']) {
            return false;
        }

        $dataArr = explode(' - ', $value['value']);
        if (count($dataArr) != 2) {
            return false;
        }

        $start = $dataArr[0].' 00:00:00';
        $end = $dataArr[1].' 23:59:59';
        $queryBuilder->andWhere($queryBuilder->expr()->between($alias.'.'.$field, "'".$start."'", "'".$end."'"));

        return true;
    }

    protected function configureListFields (ListMapper $listMapper): void {
        $listMapper
            ->add('id')
            ->add('log_type_id', null, [
                'label'     => '日志类型',
                'log_types' => GetterHelper::getEntityManager()->getRepository(LogType::class)->findAllToArray(),
                'template'  => 'backend/log/list_log_type_id.html.twig',
            ])
            ->add('description', null, ['label' => '描述'])
            ->add('ip', null, ['label' => 'IP'])
            ->add('admin_user_id', null, [
                'label'       => '系统用户',
                'admin_users' => GetterHelper::getEntityManager()->getRepository(AdminUser::class)->findAllToArray(),
                'template'    => 'backend/public/list_admin_user_id.html.twig',
            ])
            ->add('created_at', null, [
                'label'    => '创建时间',
                'format'   => 'Y-m-d H:i:s',
                'timezone' => 'PRC',
            ]);
    }

    protected function configureFormFields (FormMapper $formMapper): void {
        $formMapper
            ->add('id')
            ->add('log_type_id')
            ->add('description')
            ->add('parameter')
            ->add('admin_user_id')
            ->add('created_at');
    }

    protected function configureShowFields (ShowMapper $showMapper): void {
        $showMapper
            ->add('id')
            ->add('log_type_id')
            ->add('description')
            ->add('parameter')
            ->add('admin_user_id')
            ->add('created_at');
    }

    protected function configureRoutes (RouteCollection $collection) {
        parent::configureRoutes($collection); // TODO: Change the autogenerated stub
        $collection->clearExcept(['list']);
    }

    public function getTemplate ($name) {
        switch ($name) {
            case 'list':
                return 'backend/log/list.html.twig';
            default:
                return $this->getTemplateRegistry()->getTemplate($name);
        }
    }

    public function createQuery ($context = 'list') {
        $query = parent::createQuery($context); // TODO: Change the autogenerated stub

        // 非超级管理员只能查看自己的日志
        if (!$this->security->getUser()->isSuperAdmin()) {
            $query->andWhere(
                $query->expr()->eq($query->getRootAliases()[0].'.admin_user_id', ':admin_user_id')
            );
            $query->setParameter('admin_user_id', $this->security->getUser()->getId());
        }

        return $query;
    }

}
